import React, { useEffect, useState } from 'react'
import { Form, Input, Button, Space, Radio } from 'antd';
import AppDialog from '../../components/AppDialog'
import { editGoods } from "../../api/orders.js";
import Message from '../../components/Message'

const EditOrders = ({ visible, orderInfo, onHide }) => {

  const tailLayout = {
    wrapperCol: {
      offset: 10,
      span: 14,
    },
  };
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (visible && orderInfo.order_id) {
      form.setFieldsValue(orderInfo)
    }
  }, [orderInfo])

  // 点击确定
  const onFinish = async (values) => {
    setLoading(true)

    await editGoods(orderInfo.order_id, values).finally(() => {
      setLoading(false)
    });
    Message("success", "编辑成功");

    handleDialogClosed('success')
  };

  // 提交表单且数据验证失败后回调事件
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  // 点击取消
  const handleDialogClosed = (type) => {
    form.resetFields();
    onHide(type)
  };

  return (visible ?
    <AppDialog
      title="修改订单"
      visible={visible}
      onClosed={handleDialogClosed}
    >
      <Form
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item
          label="订单编号"
          name="order_number"
        >
          <Input disabled />
        </Form.Item>
        <Form.Item
          label="订单价格"
          name="order_price"
        >
          <Input disabled />
        </Form.Item>
        <Form.Item
          label="是否付款"
          name="pay_status"
          rules={[{ required: true, message: "请选择是否付款" }]}
        >
          <Radio.Group>
            <Radio value="0">未付款</Radio>
            <Radio value="1">已付款</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label="支付方式"
          name="order_pay"
          rules={[{ required: true, message: "请选择是否发货" }]}
        >
          <Radio.Group>
            <Radio value="0">未支付</Radio>
            <Radio value="1">支付宝</Radio>
            <Radio value="2">微信</Radio>
            <Radio value="3">银行卡</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label="是否发货"
          name="is_send"
          rules={[{ required: true, message: "请选择是否付款" }]}
        >
          <Radio.Group>
            <Radio value="否">未发货</Radio>
            <Radio value="是">已经发货</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item {...tailLayout}>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>确定</Button>
            <Button onClick={() => handleDialogClosed()}>取消</Button>
          </Space>
        </Form.Item>
      </Form>
    </AppDialog>
    : null
  )
}

export default EditOrders
